/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ClienteCadastra.java
 *
 * Created on 06/06/2011, 22:17:54
 */

package pacote;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.swing.JOptionPane;


/**
 *
 * @author Pardall
 */
public class ProdAltera extends javax.swing.JFrame {

    private EntityManager em;
    private short id;
    
    /** Creates new form ClienteCadastra */

    public ProdAltera(EntityManager exem) {
        initComponents();
        this.em = exem;

        List<Produtos> produtos = findAllprodutos();
        Object[] nomes = fillNomes(produtos);
        String nome = (String)JOptionPane.showInputDialog(null,
                            "Nome do produto",
                            "Selecione um produto",
                            JOptionPane.INFORMATION_MESSAGE,
                            null,
                            nomes,
                            nomes[0]);
        findId(nome,produtos);
        fillForm();


        List<Categorias> catego = this.getCat();
        for (Categorias i: catego){
            cat.addItem(i.getNome());
        }
    }

    private List<Categorias> getCat(){
        TypedQuery<Categorias>  query= em.createNamedQuery("Categorias.findAll", Categorias.class);
        return query.getResultList();
    }

    private Categorias getCatId(String nome){
        TypedQuery<Categorias> query = em.createNamedQuery("Categorias.findByNome", Categorias.class);
        query.setParameter("nome", nome);
        return query.getSingleResult();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        nomeProd = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        qtd = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        cat = new javax.swing.JComboBox();
        jLabel10 = new javax.swing.JLabel();
        alterar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        descr = new javax.swing.JTextArea();
        jSeparator1 = new javax.swing.JSeparator();
        preco = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Cadastrar Cliente");
        setResizable(false);

        nomeProd.setMaximumSize(new java.awt.Dimension(150, 20));
        nomeProd.setMinimumSize(new java.awt.Dimension(150, 20));
        nomeProd.setPreferredSize(new java.awt.Dimension(150, 20));
        nomeProd.setRequestFocusEnabled(false);

        jLabel2.setText("Nome:");

        jLabel3.setText("Descrição:");

        jLabel4.setText("Preço:");

        qtd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                qtdActionPerformed(evt);
            }
        });

        jLabel7.setText("Qtde em Estoque:");

        cat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                catActionPerformed(evt);
            }
        });

        jLabel10.setText("Categoria:");

        alterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imgs/check.png"))); // NOI18N
        alterar.setText("Alterar");
        alterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                alterarActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imgs/cadastrar.png"))); // NOI18N
        jLabel1.setText("Alteração de Produtos");

        descr.setColumns(20);
        descr.setRows(5);
        jScrollPane1.setViewportView(descr);

        preco.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 575, Short.MAX_VALUE)
                    .addComponent(jLabel1)
                    .addComponent(alterar, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel2)
                            .addComponent(jLabel7)
                            .addComponent(jLabel10))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(preco)
                            .addComponent(qtd, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(nomeProd, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(cat, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE, false)
                            .addComponent(jLabel2)
                            .addComponent(nomeProd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(preco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(9, 9, 9)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel7)
                            .addComponent(qtd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel10)
                            .addComponent(cat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(alterar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void alterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_alterarActionPerformed
        if (evt.getSource() == this.alterar){
            
            em.getTransaction().begin();

            Produtos prod = em.find(Produtos.class, id);
            
            prod.setNome(nomeProd.getText());
            prod.setDescricao(descr.getText());
            prod.setQtdEstoque(Short.parseShort(qtd.getText()));
            short idc = this.getCatId(cat.getSelectedItem().toString()).getId();
            prod.setPreco(Float.parseFloat(preco.getText()));
            prod.setCategoria(idc);
               
            em.getTransaction().commit();

            JOptionPane.showMessageDialog(null, "Produto alterado.");

            this.dispose();
        
        }
    }//GEN-LAST:event_alterarActionPerformed

    private void catActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_catActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_catActionPerformed

    private void qtdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_qtdActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_qtdActionPerformed

    private void fillForm (){
        Produtos p = em.find(Produtos.class,this.id);
        this.nomeProd.setText(p.getNome());
        this.preco.setText(""+p.getPreco());
        this.qtd.setText(""+p.getQtdEstoque());
        this.descr.setText(p.getDescricao());
        this.cat.setSelectedItem(p.getCategoria());
    }

    private void findId (String nome, List<Produtos> produtos){
       // String[] nomes = nomeCompleto.split(" ");
        for (Produtos p : produtos){
            if (p.getNome().equals(nome)){
                this.id = p.getId();
                break;
            }
        }
    }

    private Object[] fillNomes (List<Produtos> produtos){
        List<String> nomes = new ArrayList<String>();
        for (Produtos p : produtos){
            nomes.add(p.getNome());
        }
        return nomes.toArray();
    }

    private List<Produtos> findAllprodutos (){
        TypedQuery<Produtos> query = em.createNamedQuery("Produtos.findAll", Produtos.class);
        return query.getResultList();
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton alterar;
    private javax.swing.JComboBox cat;
    private javax.swing.JTextArea descr;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField nomeProd;
    private javax.swing.JTextField preco;
    private javax.swing.JTextField qtd;
    // End of variables declaration//GEN-END:variables

}
